package com.liuhuxiang.ribbon;

import com.alibaba.nacos.client.naming.utils.ThreadLocalRandom;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;

/**
 * 自定义的负载均衡算法
 * 写完之后，在配置类中，配置下自定义负载均衡的路径即可
 *
 * @author liuhuxiang
 * @version: CustomRibbonRule.java, 2023年03月01日 下午1:59 liuhuxiang  Exp $
 */
public class CustomRibbonRule extends AbstractLoadBalancerRule {

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }

    @Override
    public Server choose(Object o) {
        //获取当前请求的实例
        ILoadBalancer loadBalancer = this.getLoadBalancer();
        //一个服务当中会有多个实例
        List<Server> reachableServers = loadBalancer.getReachableServers();
        // 线程安全的，获取随机数
        int random = ThreadLocalRandom.current().nextInt(reachableServers.size());
        return reachableServers.get(random);

    }
}